/**
 * 系统LOGO和名称修改
 * @author xiaoxujs
 */

import { Form, GetProp, Input, message, Modal, Typography, Upload, UploadProps } from "antd"
import { FC, useEffect, useState } from "react"
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { basicIp } from "../../../../api/http";
import { Hongdian } from "../../style";
import { postBaseNameUpdate } from "../../../../api/login";
import { IBaseNameGet } from "../../../../type/login";

const { Text } = Typography;

type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

const beforeUpload = (file: FileType) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
};

const getBase64 = (img: FileType, callback: (url: string) => void) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result as string));
    reader.readAsDataURL(img);
};

const LogoName: FC<{
    open: boolean;
    logoNameValue?: IBaseNameGet;
    handleCallback: () => void;
}> = ({
    open,
    handleCallback,
    logoNameValue
}) => {
        const [form] = Form.useForm();
        const { validateFields, resetFields, setFieldsValue } = form;

        const [loading, setLoading] = useState(false);
        const [imageUrl, setImageUrl] = useState<any>();
        const [confirmLoading, setConfirmLoading] = useState(false); //确认按钮加载中

        useEffect(() => {
            if (logoNameValue) {
                setFieldsValue(logoNameValue)
                setImageUrl(logoNameValue.logo)
            }

            return () => {
            }
        }, [logoNameValue, setFieldsValue])

        const handleOk = async () => {
            const values = await validateFields()
            if (imageUrl) {
                const params = {
                    logo: imageUrl.fileId,
                    name: values.name
                }
                const { code, msg } = await postBaseNameUpdate(params) as { code: number; msg: string };
                if (code === 20000) {
                    message.success('修改成功');
                    resetFields();
                    handleCallback()
                } else {
                    message.error(msg)
                }
            } else {
                message.error('请上传LOGO')
            }
        };

        const handleCancel = () => {
            resetFields();
            handleCallback()
        };
        const props: UploadProps = {
            name: "file", //上传名字
            action: basicIp + "/sys-file/upload", // 上传地址
            method: "put", // 上传方法
            maxCount: 1, // 页面显示最多条数
            headers: {
                satoken: sessionStorage.getItem("token")!, // 请求头
                checkType: "ck-token-auth",
            },
        };
        const handleChange: UploadProps['onChange'] = (info) => {
            setConfirmLoading(true)
            if (info.file.status === 'uploading') {
                setLoading(true);
                return;
            }
            if (info.file.status === 'done') {
                if (info.file.response.code === 20000) {
                    getBase64(info.file.originFileObj as FileType, (url) => {
                        setLoading(false);
                    });
                    setImageUrl(info.file.response.data);
                } else {
                    message.error(info.file.response.msg)
                }
                setConfirmLoading(false)

            }
        };
        const normFile = (e: any) => {
            if (Array.isArray(e)) {
                return e;
            }
            return e?.fileList;
        };
        const uploadButton = (
            <button style={{ border: 0, background: 'none' }} type="button">
                {loading ? <LoadingOutlined /> : <PlusOutlined />}
                <div style={{ marginTop: 8 }}>Upload</div>
            </button>
        );
        return <Modal title="修改系统名" open={open} confirmLoading={confirmLoading} onOk={handleOk} onCancel={handleCancel}>
            <Form
                name="validate_other"
                form={form}
                labelCol={{ span: 6 }}
                wrapperCol={{ span: 16 }}
            >
                <Form.Item
                    label={
                        <span>
                            <Hongdian>*</Hongdian>
                            <span>系统LOGO</span>
                        </span>
                    }
                    valuePropName="fileList"
                    getValueFromEvent={normFile}
                >
                    <Upload
                        {...props}
                        listType="picture-card"
                        className="avatar-uploader"
                        showUploadList={false}
                        beforeUpload={beforeUpload}
                        onChange={handleChange}
                    >
                        {imageUrl ? <img src={basicIp + imageUrl.url} alt="avatar" style={{ width: '100%', height: '100%' }} /> : uploadButton}
                    </Upload>
                    <Text type="secondary">建议上传1:1比例的png格式透明文件</Text>
                </Form.Item>
                <Form.Item
                    label='系统导航标题'
                    name='name'
                    rules={[{ required: true, message: '请填写系统导航标题' }]}
                >
                    <Input />
                </Form.Item>

            </Form>
        </Modal>
    }

export default LogoName;